{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true,
    "pycharm": {
     "is_executing": true
    }
   },
   "outputs": [],
   "source": [
    "!pip install git+https://github.com/facebookresearch/segment-anything.git\n",
    "!pip install onnx\n",
    "!pip install torch"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "outputs": [],
   "source": [
    "from segment_anything import sam_model_registry\n",
    "from segment_anything.utils.onnx import SamOnnxModel\n",
    "import torch"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "outputs": [],
   "source": [
    "# Download SAM model checkpoint\n",
    "!pip install wget\n",
    "!python -m wget https://dl.fbaipublicfiles.com/segment_anything/sam_vit_b_01ec64.pth"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "is_executing": true
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "outputs": [],
   "source": [
    "# Load SAM model\n",
    "sam = sam_model_registry[\"vit_b\"](checkpoint=\"./sam_vit_b_01ec64.pth\")"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "outputs": [],
   "source": [
    "# Export images encoder from SAM model to ONNX\n",
    "torch.onnx.export(\n",
    "    f=\"vit_b_encoder.onnx\",\n",
    "    model=sam.image_encoder,\n",
    "    args=torch.randn(1, 3, 1024, 1024),\n",
    "    input_names=[\"images\"],\n",
    "    output_names=[\"embeddings\"],\n",
    "    export_params=True\n",
    ")"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "outputs": [],
   "source": [
    "# Export mask decoder from SAM model to ONNX\n",
    "onnx_model = SamOnnxModel(sam, return_single_mask=True)\n",
    "embed_dim = sam.prompt_encoder.embed_dim\n",
    "embed_size = sam.prompt_encoder.image_embedding_size\n",
    "mask_input_size = [4 * x for x in embed_size]\n",
    "dummy_inputs = {\n",
    "    \"image_embeddings\": torch.randn(1, embed_dim, *embed_size, dtype=torch.float),\n",
    "    \"point_coords\": torch.randint(low=0, high=1024, size=(1, 5, 2), dtype=torch.float),\n",
    "    \"point_labels\": torch.randint(low=0, high=4, size=(1, 5), dtype=torch.float),\n",
    "    \"mask_input\": torch.randn(1, 1, *mask_input_size, dtype=torch.float),\n",
    "    \"has_mask_input\": torch.tensor([1], dtype=torch.float),\n",
    "    \"orig_im_size\": torch.tensor([1500, 2250], dtype=torch.float),\n",
    "}\n",
    "output_names = [\"masks\", \"iou_predictions\", \"low_res_masks\"]\n",
    "torch.onnx.export(\n",
    "    f=\"vit_b_decoder.onnx\",\n",
    "    model=onnx_model,\n",
    "    args=tuple(dummy_inputs.values()),\n",
    "    input_names=list(dummy_inputs.keys()),\n",
    "    output_names=output_names,\n",
    "    dynamic_axes={\n",
    "        \"point_coords\": {1: \"num_points\"},\n",
    "        \"point_labels\": {1: \"num_points\"}\n",
    "    },\n",
    "    export_params=True,\n",
    "    opset_version=17,\n",
    "    do_constant_folding=True\n",
    ")"
   ],
   "metadata": {
    "collapsed": false
   }
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}
